<template>
  <div class="con">
    <el-form
      :model="formData"
      label-width="80px"
      :inline="true"
      ref="formEle"
      class="flex formTop"
      :rules="rules"
    >
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="formData.deptName" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formEle)">查询</el-button>
        <el-button @click="resetForm(formEle)">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <div class="table-list">
      <div class="btnTop">
        <el-button type="primary" @click="handleAdd">创建</el-button>
      </div>
      <el-table :data="DeptList" stripe style="width: 100%" row-key="_id">
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          :prop="item.property"
          :label="item.label"
          :formatter="item.formatter"
        ></el-table-column>
        <el-table-column label="操作" class="last-btn">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogFormType == 'Edit' ? '编辑' : '新增用户'"
    @closed="clearDialog(formEl)"
  >
    <el-form
      :model="dialogFormData"
      :label-width="formLabelWidth"
      ref="dialogForm"
    >
      <el-form-item label="父级菜单" prop="parentId">
        <el-cascader
          v-model="dialogFormData.parentId"
          :options="DeptList"
          :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogConfirm(dialogForm)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { DeptDialogForm, GetDeptInfo, reqResult } from "@/types/type";
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import request from "../api/requestApi";
import { formateDate, showMassage } from "../untils/common";
onMounted(() => {
  reqDeptList();
});
// 表单数据
const formEle = ref<FormInstance>(); //实例
let formData = reactive({
  deptName: "",
});
let DeptList = ref<GetDeptInfo[]>([]);
const rules = reactive<FormRules>({
  deptName: [
    { required: true, message: "请输入部门名称", trigger: "blur" },
    { min: 3, max: 5, message: "长度在1个字符到5个字符之间", trigger: "blur" },
  ],
});
// const dialogrules = 
let columns = ref([
  {
    property: "deptName",
    label: "部门名称",
  },
  {
    property: "userName",
    label: "负责人",
  },
  {
    property: "updateTime",
    label: "更新时间",
    formatter(row: string, column: string, cellValue: string) {
      return formateDate(new Date(cellValue));
    },
  },
  {
    property: "createTime",
    label: "创建时间",
    formatter(row: string, column: string, cellValue: string) {
      return formateDate(new Date(cellValue));
    },
  },
]);
// 请求表单数据
const reqDeptList = async () => {
  let res = (await request.getDeptList({ ...formData })) as reqResult<
    GetDeptInfo[]
  >;
  DeptList.value = res.data;
};

// 查询
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      reqDeptList();
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 创建、编辑和删除
const handleAdd = () => {
  openDialog("Add");
};
const handleEdit = (index: number, row: GetDeptInfo) => {
  Object.assign(dialogFormData, row);
  openDialog("Edit");
};
const handleDelete = (index: number, row: GetDeptInfo) => {
  dialogFormType.value = "del";
};

// dialog 对话框
const dialogFormVisible = ref(false); // 开关
const dialogFormType = ref<string>("");
// 打开模态框
function openDialog(type: string) {
  dialogFormVisible.value = true;
  dialogFormType.value = type;
}
function clearDialog(formEl: FormInstance) {
  dialogFormVisible.value = false;
  formEl.resetFields();
  goinitialize()
}
// 提交
function dialogConfirm(formEl: FormInstance) {
  if (!formEl) return;
  if (dialogFormData.parentId === null) {
    dialogFormData.parentId = [null];
  }
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = (await request.OperateDept({
        dialogFormType: dialogFormType.value,
        ...dialogFormData,
      })) as reqResult<null>;
      if (res.code == 200) {
        showMassage(res.msg, "success");
        reqDeptList();
      } else {
        showMassage(res.msg, "error");
      }
      dialogFormVisible.value = false;
    }
  });
  formEl.resetFields();
  goinitialize();
}

// 表单实例对象
let dialogForm = ref<FormInstance>();
let formLabelWidth = ref<string>("100px");
// 表单数据
let dialogFormData = reactive<DeptDialogForm>({
  parentId: [null],
  deptName: "",
  userName: "",
  userEmail: "",
});
// 初始化表单数据
const goinitialize = () => {
  let initialize = {
    parentId: [null],
    deptName: "",
    userName: "",
    userEmail: "",
  };
  dialogFormData = initialize;
};
</script>

<style lang="postcss" scoped>
.con {
  @apply flex-1 flex flex-col;
  width: 100%;
}
.formTop {
  height: 60px;
  padding: 20px;
  @apply bg-light-50;
  line-height: 60px;
  border-radius: 5px;
  .el-form-item {
    margin-bottom: 0;
    align-self: center;
  }
}
.table-list {
  @apply bg-light-50 flex-1 flex flex-col;
  border-radius: 5px;
  overflow: hidden;
  margin: 20px 0 0 0;
  .btnTop {
    padding: 20px;
  }
  .el-pagination {
    margin: auto auto 0;
    height: 50px;
  }
}
.el-form :deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
.el-table :deep(.el-table__cell) {
  padding: 15px 0;
}
</style>
